<template>
  <section class="personal">
    <headerUtil :obj="headerObj" @closeFn="closeLivingFn">PK直播间</headerUtil>
    <div class="video-wrap">
          <video class="anchorVideo" @click="lastChooseAnchorId = anchorConfig.anchorId" :poster="anchorImg" />
          <video class="pkObjVideo" @click="lastChooseAnchorId = pkObjId" :poster="pkObjImg" />
    </div>
    <div class="bar-wrap">
      <div class="bar">
        <div class="position-bar" :style="{left: barLeft+'%'}">
          <div class="bar-left"></div>
        <div class="bar-right"></div>
        </div>
      </div>
    </div>
    <div :style="{display: canvasBool?'block':'none'}" class="svga-wrap" ref="svgaWrap"></div>
    <div class="content" @scroll.passive="scrollData" ref="scrollOut">
      <div class="item-wrap"  v-for="(item, index) in chatList" :key="index">
        <div :class="{'face-img':true, 'right-wrap':item.msg.userId == anchorConfig.userId, 'left-wrap':item.msg.userId != anchorConfig.userId}" :style="{background: `url(${item.msg.senderImg}) no-repeat center`}"></div>
        <div :class="{'content-wrap':true, 'right-wrap':item.msg.userId == anchorConfig.userId, 'left-wrap':item.msg.userId != anchorConfig.userId}">
          <div class="name">{{item.msg.senderName}}</div>
          <div class="text">{{item.msg.content}}</div>
          </div>
      </div>
    </div>
    <commonNavUtil :livingType="2" @sendInfoFn="sendReview" @selectSvgaFn="sendGiftFn" @connectFn="connectLiving"></commonNavUtil>
  </section>
</template>
<script>
import reqApis from "../../req/reqApis.js";
import headerUtil from "../base/common/headerUtil.vue";
import commonNavUtil from "../base/common/commonNavUtil.vue";

import SVGA from "svgaplayerweb";
// import Client from '../../req/common.js';


import {showNotify} from 'vant';

export default {
  components: {
    headerUtil,
    commonNavUtil
  },
  data () {
    return {
      barLeft: -50,
      lastChooseAnchorId: null,
      pkObjId:null,
      pkObjImg: null,
      anchorImg: null,
      canvasBool: false,
      roomId: this.$route.query.roomId || 0,
      anchorConfig: {},
      user: {},
      websock: null,
      chatList: [],
      headerObj:{
        showType: 2,
        closeBtn: false
      },
      list: [],
      pageIndex: 1,
      isStop: false,
      canvas: {},
      player: {},
      parser: {}
    }
  },
  created() {
    if(this.roomId != null){
      reqApis.anchorConfigApi({roomId: this.roomId}).then(res => {
        this.anchorConfig = res.data;
        this.anchorImg = res.data.anchorImg;
        this.headerObj.closeBtn = this.anchorConfig.anchor;
        console.log(989, res.data)
        this.connectImServer();
      }).catch(err => {
        showNotify({ type: 'danger', message: err.msg});

      })
    }
    
    // this.getUserFn();
  },
  mounted(){
    this.initSvga();
    
  },
  methods: {
  initSvga() {
    this.canvas = this.$refs.svgaWrap;
    this.player = new SVGA.Player(this.canvas);
    this.parser = new SVGA.Parser(this.canvas);
  },
  changeBarWidth(pkNum) {
      console.log(pkNum);
      this.barLeft = this.barLeft + 10;
      // let pkBar = document.getElementById("pkBar");
      // pkBar.style.width = (pkNum + '%');
  },
  sendGiftFn(giftObj) {
    if(this.lastChooseAnchorId == '' || this.lastChooseAnchorId == null) {
        ElMessage({
                message: '请选择接受礼物的主播',
                grouping: true,
                type: 'error'});
                return;
    }
    let params = {
        giftId: giftObj.id,
        roomId: this.roomId,
        receiverId: this.lastChooseAnchorId,
        senderUserId: this.anchorConfig.userId,
        type: 1
      }; 
      reqApis.sendGiftApi(params).then(res => {
      }).catch(err => {
              ElMessage({
                message: err.msg,
                grouping: true,
                type: 'error'});
            })
  },

  //渲染礼物特效svga
  playGiftSvga(url) {
      this.canvasBool = true;
      this.player.clearsAfterStop = true;
      this.player.stopAnimation();
      this.parser.load(url, (videoItem) => {
          this.player.loops = 1; // 设置循环播放次数是1
          this.player.setVideoItem(videoItem);
          this.player.startAnimation();
          this.player.onFinished(() => {
              console.log("动画停止了！！！");
              this.canvasBool = false;
          });
      });
      
      
  },
  connectLiving() {
      console.log('连线');
      reqApis.onlinePkApi({roomId: this.roomId}).then(res => {
        this.pkObjId = res.data.pkObjId;
        this.pkObjImg = res.data.pkObjAvatar;
        this.$message.success('连线成功');
      }).catch(err => {
        this.$message.success(err.msg);
      })
  },
    connectImServer() {
      reqApis.getImConfigApi({}).then(res => {
        let url = `ws://${res.data.wsImServerAddress}/${res.data.token}/${this.anchorConfig.userId}/1001/${+this.roomId}`;
        // let url = "ws://192.168.2.166:9991/8d6b6c4f-1fb5-41bc-b0ff-77b258eb821d/100001/1001/"+this.roomId;
        console.log(url);
        this.websock = new WebSocket(url);
        this.websock.onmessage = this.websocketOnMessage;
        this.websock.onopen = this.websocketOnOpen;
        this.websock.onerror = this.websocketOnError;
        this.websock.onclose = this.websocketClose;
        console.log('初始化ws服务器');
        
      }).catch(err => {

      });
      // let url = "ws://"+that.imServerConfig.wsImServerAddress+"/" + that.imServerConfig.token+"/"+that.initInfo.userId+"/1001/"+this.roomId;
      
    },
    closeLivingFn() {
      reqApis.closeLivingApi({roomId: this.roomId}).then(res => {
        this.$router.push("/livingRoomList");
      }).catch(err => {
        


      })
    },
    scrollData() {
      let outH = this.$refs.scrollOut.scrollHeight,
          currentH = this.$refs.scrollOut.offsetHeight,
          offH = this.$refs.scrollOut.scrollTop;
        if(currentH + offH >= (outH-1)){
          this.pageIndex += 1;
        }
    },
     websocketOnOpen() {
        console.log('初始化连接建立');
    },

    websocketOnError() {
        console.error('出现异常');
    },
    websocketClose(e) {  //关闭
        console.log('断开连接', e);
    },
     websocketSend(data) {//数据发送
        this.websock.send(data);
    },
    startHeartBeatJob() {
        console.log('首次登录成功');
        //发送一个心跳包给到服务端
        let jsonStr = {"userId": this.anchorConfig.userId, "appId": 10001};
        let bodyStr = JSON.stringify(jsonStr);
        let heartBeatJsonStr = {"magic": 19231, "code": 1004, "len": bodyStr.length, "body": bodyStr};
        setInterval(() => {
            this.websocketSend(JSON.stringify(heartBeatJsonStr));
        }, 3000);
    },
   
    websocketOnMessage(e) { //数据接收
            let wsData = JSON.parse(e.data);
            if(wsData.code == 1001) {
                this.startHeartBeatJob();
            } else if (wsData.code == 1003) {
                // let respData = JSON.parse(Client.utf8ByteToUnicodeStr());
              let respData = JSON.parse(wsData.bodyStr);
                //属于直播间内的聊天消息
                if(respData.bizCode==5555) {
                    let respMsg = JSON.parse(respData.data);
                    let sendMsg = {"userId": respMsg.userId, "content": respMsg.content, "senderName": respMsg.senderName, "senderImg": respMsg.senderAvtar};
                    let msgWrapper = {"msgType": 1, "msg": sendMsg};
                    console.log(33311, sendMsg);
                    this.chatList.push(msgWrapper);
                    //注意让滑轮滚到底
                    // this.$nextTick(() => {
                    //     var div = document.getElementById('talk-content-box')
                    //     div.scrollTop = div.scrollHeight
                    // })
                    //发送ack确认消息
                }else if(respData.bizCode == 5557){
                    //送礼失败
                    let respMsg = JSON.parse(respData.data);
                    this.$message.error(respMsg.msg);
                } else if (respData.bizCode == 5558) {
                  console.log(1111222, respData)
                    //pk送礼成功
                    let respMsg = JSON.parse(respData.data);
                    //说明已经有pk结果了
                    if (respMsg.winnerId != null) {
                        this.pkEnd = true;
                        this.$message.success("恭喜主播" + respMsg.winnerId+"pk获胜");
                        return;
                    } 
                    console.log(respMsg);
                    // 默认值
                    if(respMsg.giftId == 1){
                      this.playGiftSvga(new URL("../../assets/svga/爱心.svga", import.meta.url));
                    }else if(respMsg.giftId == 2) {
                      this.playGiftSvga(new URL("../../assets/svga/女巫.svga", import.meta.url));
                    }else if(respMsg.giftId == 3) {
                      this.playGiftSvga(new URL("../../assets/svga/跑车.svga", import.meta.url));
                    }else if(respMsg.giftId == 4) {
                      this.playGiftSvga(new URL("../../assets/svga/头像.svga", import.meta.url));
                    }
                    // this.playGiftSvga(respMsg.url);
                    this.changeBarWidth(respMsg.pkNum);
                } else if (respData.bizCode == 5559) {
                    this.$message.success("pk用户已上线");
                    let respMsg = JSON.parse(respData.data);
                    this.pkObjId = respMsg.pkObjId;
                    this.pkObjImg = respMsg.pkObjAvatar;
                }
                this.sendAckCode(respData);
            }
        },
        sendAckCode(respData) {
            let jsonStr = {"userId": this.anchorConfig.userId, "appId": 10001,"msgId":respData.msgId};
            let bodyStr = JSON.stringify(jsonStr);
            let ackMsgStr = {"magic": 19231, "code": 1005, "len": bodyStr.length, "body": bodyStr};
            this.websocketSend(JSON.stringify(ackMsgStr));
        },
        sendReview(info){
            if (info == '') {
                ElMessage({
                message: "评论不能为空",
                grouping: true,
                type: 'warning'});
                return;
            }
            let sendMsg = {"userId":this.anchorConfig.userId, "content": info, "senderName": this.anchorConfig.watcherNickName, "senderImg": this.anchorConfig.watcherAvatar};
            let msgWrapper = {"msgType": 1, "msg": sendMsg};
            this.chatList.push(msgWrapper);
            //发送评论消息给到im服务器
            let msgBody = {"roomId":this.roomId,"type":1,"content":info,  "senderName": this.anchorConfig.watcherNickName, "senderAvtar": this.anchorConfig.watcherAvatar};
            let jsonStr = {"userId": this.anchorConfig.userId, "appId": 10001,"bizCode":5555,"data":JSON.stringify(msgBody)};
            let bodyStr = JSON.stringify(jsonStr);
            console.log('发送消息');
            let reviewMsg = {"magic": 19231, "code": 1003, "len": bodyStr.length, "body": bodyStr};
            console.log(JSON.stringify(reviewMsg));
            this.websocketSend(JSON.stringify(reviewMsg));
        
        }
  },
  
  
}
</script>
<style lang="less" scoped>
.personal {
  width: 3.75rem;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  .bar-wrap {
    width: 3.75rem;
    height: 0.5rem;
    display: flex;
    align-items: center;
    justify-content: center;
    .bar {
      width: 3rem;
      height: 0.3rem;
      background: #aaa;
      border-radius: 0.15rem;
      overflow: hidden;
      position: relative;
    }
    .position-bar {
      width: 6rem;
      height: 0.3rem;
      background: #aaa;
      position: absolute;
      -moz-transition: width .6s ease;
      -webkit-transition: width .6s ease;
      transition: width .6s ease;
      .bar-left {
        width: 3rem;
        height: 0.3rem;
        background: red;
        float: left;
      }
      .bar-right {
        width: 3rem;
        height: 0.3rem;
        background: blue;
        float: right;

      }
    }
  }
  .video-wrap {
    width: 3.75rem;
    height:2.5rem;
    background: red;
    display: flex;
    align-items: center;
    justify-content: center;
    .anchorVideo {
      width: 1.5rem;
      display: inline-block;
    }
    .pkObjVideo {
      width: 1.5rem;
      display: inline-block;
    }
  }
  .content {
    flex: 1;
    overflow-y: auto;
    .list {
      background: white;
      overflow: hidden;
    }
    .item-wrap {
      width: 3.75rem;
      min-height: 0.5rem;
      margin: .1rem 0;
      .face-img {
        width: 0.5rem;
        height: 0.5rem;
        background-size: contain !important;
      }
    }
    .left-wrap {
      float: left;
      .text {
        background: white;
      }
    }
    .right-wrap {
      float: right;
      text-align: right;
      .text {
        background: #9adc9a;
      }
    }
    .content-wrap {
      display: inline-block;
      min-height: 0.5rem;
      max-width: 3.2rem;
      padding: 0.05rem;
      .name {
        font-size: 0.12rem;
        padding:.02rem;
      }
      .text {
        display: inline-block;
        word-wrap: break-word;
        font-size: 0.16rem;
        line-height: 0.2rem;
        padding: 0.05rem;
        border-radius: 0.04rem;
      }
    }
  }
  .svga-wrap {
    z-index: 999;
    position: absolute;
    top:  -10%;
    height: 70%;
    width: 100%;
  }
}
</style>

